<template>
  <div class="page">
    <!-- 顶部导航 -->
    <div class="nav">
      <div class="nav-content">
        <div class="nav-left">
          <el-button type="primary" @click="router.back()">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <el-button type="success" @click="toHome">
            <el-icon><House /></el-icon>
            返回主页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main" v-loading="loading">
      <!-- 店铺信息 -->
      <div class="shop-bar">
        <div class="shop-info">
          <img :src="farmInfo.logoUrl" class="shop-logo" />
          <div class="shop-detail">
            <div class="shop-name">{{ farmInfo.farmName }}</div>
            <div class="shop-desc">{{ farmInfo.description }}</div>
          </div>
        </div>
      </div>

      <div class="detail-content">
        <!-- 左侧图片展示 -->
        <div class="left">
          <div class="preview">
            <img :src="currentImage" class="main-img" @click="previewImage" />
          </div>
          <div class="thumbs">
            <img 
              v-for="(img, index) in product.images" 
              :key="img.imageUrl"
              :src="img.imageUrl"
              :class="['thumb-img', { active: index === currentIndex }]"
              @click="currentIndex = index"
            />
          </div>
        </div>

        <!-- 右侧商品信息 -->
        <div class="right">
          <div class="product-title">
            {{ product.name }}
            <el-icon 
              :class="['favorite-icon', { 'is-favorite': isFavorite }]"
              @click="toggleFavorite"
            >
              <Star />
            </el-icon>
          </div>
          
          <div class="price-box">
            <div class="price-line">
              <span class="price-label">价格</span>
              <span class="price-symbol">¥</span>
              <span class="price-value">{{ product.price }}</span>
              <span class="price-unit">/斤</span>
            </div>
            <div class="promotion">
              <span class="promo-tag">每满200减30</span>
            </div>
          </div>

          <div class="service-box">
            <div class="service-item">
              <span class="label">运费</span>
              <span class="value">免运费</span>
            </div>
            <div class="service-item">
              <span class="label">发货地</span>
              <span class="value">{{ farmInfo.address }}</span>
            </div>
            <div class="service-item">
              <span class="label">发货人</span>
              <span class="value">{{ farmInfo.description }}</span>
            </div>
          </div>

          <div class="quantity-box">
            <span class="label">数量</span>
            <div class="quantity-control">
              <button class="minus" @click="decrease" :disabled="quantity <= 1">-</button>
              <input type="number" v-model="quantity" min="1" :max="product.stock" />
              <button class="plus" @click="increase" :disabled="quantity >= product.stock">+</button>
              <span class="stock">库存 {{ product.stock }} 件</span>
            </div>
          </div>

          <div class="action-box">
            <button 
              class="buy-now" 
              :disabled="product.stock <= 0"
              @click="handleBuy"
            >
              立即购买
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, House, Star } from '@element-plus/icons-vue'
import { getProductDetail, addToFavorites, removeFromFavorites, checkIsFavorite } from '@/api/products'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const currentIndex = ref(0)
const quantity = ref(1)
const selectedColor = ref('蓝色')
const selectedSize = ref('M')
const isFavorite = ref(false)

const farmInfo = ref({})
const product = ref({
  name: '',
  price: 0,
  stock: 0,
  images: [],
})

const currentImage = computed(() => {
  if (product.value.images && product.value.images.length > 0) {
    return product.value.images[currentIndex.value].imageUrl
  }
  return ''
})

const increase = () => {
  if (quantity.value < product.value.stock) {
    quantity.value++
  }
}

const decrease = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const previewImage = () => {
  // 实现图片预览逻辑
}

const toHome = () => {
  router.push({ name: 'home' }) // 使用正确的路由名称
}

const toggleFavorite = async () => {
  try {
    const productId = route.params.productId
    console.log('开始切换收藏状态, 商品ID:', productId)
    console.log('当前收藏状态:', isFavorite.value ? '已收藏' : '未收藏')
    
    if (isFavorite.value) {
      // 取消收藏
      console.log('准备调用取消收藏接口...')
      const res = await removeFromFavorites(productId)
      console.log('取消收藏接口返回:', res)
      
      if (res.code === 200) {
        isFavorite.value = false
        console.log('更新后的收藏状态:', isFavorite.value ? '已收藏' : '未收藏')
        ElMessage.success('已取消收藏')
      } else {
        ElMessage.error(res.message || '取消收藏失败')
      }
    } else {
      // 添加收藏
      console.log('准备调用添加收藏接口...')
      const res = await addToFavorites(productId)
      console.log('添加收藏接口返回:', res)
      
      if (res.code === 200) {
        isFavorite.value = true
        console.log('更新后的收藏状态:', isFavorite.value ? '已收藏' : '未收藏')
        ElMessage.success('收藏成功')
      } else {
        ElMessage.error(res.message || '收藏失败')
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const checkFavoriteStatus = async () => {
  try {
    const productId = route.params.productId
    console.log('开始检查收藏状态, 商品ID:', productId)
    
    const res = await checkIsFavorite(productId)
    console.log('检查收藏状态接口返回:', res)
    
    // 只有当接口返回成功且data为true时才显示橙色星标
    if (res.code === 200) {
      isFavorite.value = Boolean(res.data) // 确保转换为布尔值
      console.log('收藏状态:', isFavorite.value ? '已收藏(橙色星标)' : '未收藏(灰色星标)')
    } else {
      console.warn('获取收藏状态失败:', res.message)
      isFavorite.value = false // 失败时显示未收藏状态（灰色星标）
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
    isFavorite.value = false // 错误时显示未收藏状态（灰色星标）
  }
}

const loadProductDetail = async () => {
  try {
    loading.value = true
    const productId = route.params.productId
    const res = await getProductDetail(productId)
    
    if (res?.product) {
      const { product: productData, images, farm } = res
      
      farmInfo.value = {
        farmName: farm?.farmName || '未知农场',
        description: farm?.farmDescription || '暂无描述',
        address: farm?.farmAddress || '暂无地址信息',
        logoUrl: farm?.farmImages?.[0]?.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      
      product.value = {
        name: productData.productName,
        price: productData.price,
        stock: productData.stock,
        images: images || []
      }
    } else {
      ElMessage.error('获取商品详情失败')
      router.back()
    }
  } catch (error) {
    ElMessage.error('加载失败，请重试')
    router.back()
  } finally {
    loading.value = false
  }
}

// 处理购买
const handleBuy = async () => {
  try {
    // 检查用户是否登录
    const userId = sessionStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    const productId = route.params.productId
    if (!productId) {
      ElMessage.error('商品ID不存在')
      return
    }

    if (quantity.value <= 0 || quantity.value > product.value.stock) {
      ElMessage.error('请选择正确的购买数量')
      return
    }

    console.log('准备添加商品到购物车:', {
      productId: parseInt(productId),
      quantity: quantity.value
    })

    // 调用后端接口，将商品信息存入Redis
    const response = await request({
      url: '/api/products/purchase/prepare',
      method: 'post',
      params: {  // 使用 params 而不是 data，因为后端使用 @RequestParam
        productId: parseInt(productId),
        quantity: quantity.value
      }
    })

    console.log('服务器响应:', response)

    // 显示成功消息
    ElMessage.success('商品已加入购物车')
    // 重新加载商品详情
    await loadProductDetail()
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败，请稍后重试')
  }
}

onMounted(async () => {
  console.log('组件挂载，开始加载数据...')
  console.log('路由参数:', route.params)
  
  await loadProductDetail()
  console.log('商品详情加载完成')
  
  await checkFavoriteStatus()
  console.log('收藏状态检查完成')
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f4f4f4;
}

.nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  z-index: 100;
}

.nav-content {
  max-width: 1400px;
  height: 100%;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
}

.nav-left {
  display: flex;
  gap: 10px;
}

.back-btn {
  border: none;
  background: none;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.main {
  padding-top: 50px;
}

.shop-bar {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  padding: 15px 0;
}

.shop-info {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.shop-logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 1px solid #e8e8e8;
}

.shop-detail {
  flex: 1;
}

.shop-name {
  font-size: 18px;
  color: #333;
  margin-bottom: 5px;
}

.shop-desc {
  font-size: 14px;
  color: #666;
}

.detail-content {
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
  display: flex;
  gap: 30px;
}

.left {
  width: 460px;
  background: #fff;
  padding: 20px;
}

.preview {
  width: 100%;
  height: 460px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.main-img {
  max-width: 100%;
  max-height: 100%;
  cursor: zoom-in;
}

.thumbs {
  display: flex;
  gap: 10px;
}

.thumb-img {
  width: 60px;
  height: 60px;
  border: 2px solid transparent;
  cursor: pointer;
  object-fit: cover;
}

.thumb-img.active {
  border-color: #ff4400;
}

.right {
  flex: 1;
  min-width: 0;
  background: #fff;
  padding: 20px;
}

.product-title {
  font-size: 24px;
  color: #ff6b00;
  margin-bottom: 20px;
  line-height: 1.4;
  font-weight: bold;
  text-align: center;
  padding: 20px 0;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.price-box {
  background: #FFF2E8;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.price-line {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
}

.price-label {
  font-size: 16px;
  color: #666;
  margin-right: 10px;
}

.price-symbol {
  font-size: 22px;
  color: #ff4400;
  margin-right: 4px;
}

.price-value {
  font-size: 32px;
  color: #ff4400;
  font-weight: bold;
}

.price-unit {
  font-size: 16px;
  color: #666;
  margin-left: 4px;
}

.promotion {
  display: flex;
  gap: 8px;
}

.promo-tag {
  background: #ff4400;
  color: #fff;
  padding: 2px 8px;
  border-radius: 2px;
  font-size: 12px;
}

.service-box {
  background: #f8f8f8;
  padding: 15px 20px;
  margin: 20px 0;
  border-radius: 4px;
}

.service-item {
  display: flex;
  margin-bottom: 10px;
}

.service-item:last-child {
  margin-bottom: 0;
}

.service-item .label {
  width: 70px;
  color: #666;
}

.service-item .value {
  color: #333;
}

.quantity-box {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.quantity-control button {
  width: 30px;
  height: 30px;
  border: 1px solid #e8e8e8;
  background: #fff;
  cursor: pointer;
}

.quantity-control button:disabled {
  cursor: not-allowed;
  color: #ccc;
}

.quantity-control input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #e8e8e8;
  margin: 0 5px;
}

.stock {
  margin-left: 20px;
  color: #666;
}

.action-box {
  display: flex;
  gap: 20px;
  margin-top: 30px;
}

.action-box button {
  width: 180px;
  height: 48px;
  border-radius: 24px;
  border: none;
  font-size: 16px;
  cursor: pointer;
}

.action-box button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.buy-now {
  background: #ff4400;
  color: #fff;
}

.buy-now:hover {
  background: #f30;
}

.favorite-icon {
  cursor: pointer;
  font-size: 24px;
  color: #dcdfe6;
  transition: all 0.3s;
}

.favorite-icon:hover {
  transform: scale(1.1);
}

.favorite-icon.is-favorite {
  color: #ff9900 !important;
}
</style>